package com.mlethe.library.utils.encrypt;

import android.util.Base64;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mlethe on 2018/1/11.
 */
public class StringUtil {
    private static String original = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    private static String replace;

    /**
     * 初始化
     * @param str
     */
    public static void init(String str) {
        replace = str;
    }

    /**
     * 生成replace
     */
    public static String getReplace() {
        List<Character> list = new ArrayList<>();
        char[] strc = original.toCharArray();
        for (char c : strc) {
            list.add(c);
        }
        // 打乱顺序
        Collections.shuffle(list);
        String str = "";
        for (Character c : list) {
            str += c;
        }
        return str;
    }

    /**
     * 加密
     *
     * @param str
     * @return
     */
    public static String encode(String str) {
        if (replace == null || str == null) {
            return null;
        }
        // Base64 加密
        str = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
        str = str.trim();
        char[] str1 = original.toCharArray();
        char[] str2 = replace.toCharArray();
        Map<Character, Character> map = new HashMap<>();
        for (int i = 0; i < str1.length; i++) {
            map.put(str1[i], str2[i]);
        }
        char[] encode = str.toCharArray();
        String newStr = "";
        for (int i = 0; i < encode.length; i++) {
            newStr += map.get(encode[i]);
        }
        return newStr;
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static String decode(String str) {
        if (replace == null || str == null) {
            return null;
        }
        str = str.trim();
        char[] str1 = original.toCharArray();
        char[] str2 = replace.toCharArray();
        Map<Character, Character> map = new HashMap<>();
        for (int i = 0; i < str1.length; i++) {
            map.put(str2[i], str1[i]);
        }
        char[] decode = str.toCharArray();
        String newStr = "";
        for (int i = 0; i < decode.length; i++) {
            newStr += map.get(decode[i]);
        }
        return new String(Base64.decode(newStr, Base64.DEFAULT));
    }
}
